﻿using System;
using System.IO;
using System.Xml.Serialization;

namespace CommonNet48.SerializerUtils
{
    /// <summary>
    /// XML序列化工具类
    /// </summary>
    public class XmlHelper
    {

        public static void SaveToXml<T>( T sourceObj, string filePath, string xmlRootName)
        {


                using (StreamWriter writer = new StreamWriter(filePath))
                {
                    XmlSerializer xmlSerializer = string.IsNullOrWhiteSpace(xmlRootName) ?
                        new XmlSerializer(typeof(T)) :
                        new XmlSerializer(typeof(T), new XmlRootAttribute(xmlRootName));
                    xmlSerializer.Serialize(writer, sourceObj);
                }
            
        }

        /// <summary>
        /// 对象序列化成XML文件
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="path">XML文件完整路径及名称</param>
        /// <param name="obj">对象</param>
        /// <param name="root">根元素名称</param>
        public static void SaveToXML<T>(T obj, string path, string root = "")
        {
            Type type = typeof(T);
            using (StreamWriter writer = new StreamWriter(path))
            {
                XmlSerializer objXmlSerializer = root.Trim().Length == 0 ? new XmlSerializer(type) : new XmlSerializer(type, new XmlRootAttribute(root));
                objXmlSerializer.Serialize(writer, obj);
            }
        }

        /// <summary>
        /// XML文件反序列化成对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="path">XML文件完整路径及名称</param>
        /// <param name="root">根元素名称</param>
        /// <returns></returns>
        public static T LoadFromXML<T>(string path, string root = "")
        {
            if (!File.Exists(path)) return default;
            using (StreamReader reader = new StreamReader(path))
            {
                //XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

                XmlSerializer xmlSerializer = root.Trim().Length == 0 ? new XmlSerializer(typeof(T)) : new XmlSerializer(typeof(T), new XmlRootAttribute(root));
                return (T)xmlSerializer.Deserialize(reader);
            }
        }

    }
}
